package com.quartz.config;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

@Configuration
public class SchedulerConfiguration {

    @Autowired
    public DataSource dataSource;

    @Bean
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setSchedulerName("scheduler");
        // 设置连接池
        factory.setDataSource(dataSource);
        factory.setApplicationContextSchedulerContextKey("application");
        // 设置properties配置文件
        factory.setQuartzProperties(quartzProperties());
        // 设置线程池
        factory.setTaskExecutor(schedulerThreadPool());
        // 设置延迟时间
        factory.setStartupDelay(0);
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        // 配置加载properties文件路径
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        // 读取数据
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Bean
    public Executor schedulerThreadPool(){
        // 创建线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置线程池大小，根据系统决定Runtime.getRuntime().availableProcessors()
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        // 设置最大线程池数量
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
        // 设置队列数量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors());
        return executor;
    }
}
